﻿using KqAutoDesign.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using static System.Net.Mime.MediaTypeNames;

namespace KqAutoDesign.Utilities
{
    public class ScriptOperator
    {
        public ScriptOperator(string script)
        {
            _script = script;
            ScriptParams = new List<ParamData>();
        } 
        private string _script;
        public List<ParamData> ScriptParams 
        {
            get;set;
        }
        public bool GetAllParams()
        {
            if(string.IsNullOrEmpty(_script))
                return false;
            string toFindLeft = "{[(";
            string toFindRight = ")]}";
            int runIndex = 0;
            try
            {
                while (runIndex != -1)
                {
                    
                    runIndex = _script.IndexOf(toFindLeft, runIndex);
                    //data.Start = runIndex;
                    int start = runIndex;
                    if (runIndex != -1)
                    {
                        runIndex += toFindLeft.Length; // 移动到下一个可能的匹配位置
                        var next = _script.IndexOf(toFindRight, runIndex);
                        if (next != -1)
                        {
                            //data.Content = _script.Substring(runIndex, next - runIndex);
                            string content = _script.Substring(runIndex, next - runIndex);
                            //Convert.ToInt32(data.Content);
                            runIndex = next + toFindRight.Length - 1; // 移动到下一个可能的匹配位置
                            //data.End = runIndex;
                            int end = runIndex;
                            if(ScriptParams.Exists(x=>x.Content== content))
                            {
                                ScriptParams.FirstOrDefault(x => x.Content == content).StartEnd.Add(new KeyValuePair<int, int>(start, end));
                            }
                            else
                            {
                                ParamData data = new ParamData();
                                data.Content = content;
                                data.StartEnd.Add(new KeyValuePair<int, int> ( start, end ));
                                ScriptParams.Add(data);
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception)
            {
                ScriptParams.Clear();
                return false;
            }
            
        }
    }
}
